// pages/orderList/orderList.js
import {
  getOrderByStatus,
  receivedGoods
} from '../../network/index.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: "1",
    tabList: [{
      title: "待支付",
      key: "1"
    }, {
      title: "待发货",
      key: "2"
    }, {
      title: "待收货",
      key: "3"
    }, {
      title: "已完成",
      key: "4"
    }, {
      title: "已取消",
      key: "5"
    }],
    orderList: [],
    total: 0,
    page: 1,
    pageSize: 10,
    isOK: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  onShow() {
    // 业务请求开始 模拟进入页面即发起请求
    this.init();
  },

  init() {
    this.setData({
      orderList: [],
      total: 0,
      page: 1,
      pageSize: 10,
      isOK: false,
    });
    console.log(this.data.active)
    this.getOrderByStatus();
  },
  // 切换tab
  onChange({
    detail
  }) {
    this.setData({
      active: detail.name
    });
    this.init();
  },

  // 获取订单信息
  async getOrderByStatus() {
    getOrderByStatus({
      page: this.data.page,
      pageSize: this.data.pageSize,
      status: this.data.active
    }).then((result) => {
      const {
        items,
        total
      } = result;
      const orderList = [...this.data.orderList, ...items];
      this.setData({
        total,
        page: this.data.page++,
        orderList
      })
    })
    if (this.data.total <= this.data.orderList.length) {
      this.setData({
        isOK: true
      });
    }
    wx.hideLoading();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isOK) {
      return;
    }
    this.getOrderByStatus();
  },
  // 继续支付
  onPay(event) {
    wx.navigateTo({
      url: `../pay/pay?id=${event.currentTarget.dataset.id}`,
    });
  },
  // 确认收货
  onOk(event) {
    const that = this;
    wx.showModal({
      title: '确认收货',
      content: '点击确认将完成订单',
      async success(res) {
        if (res.confirm) {
          receivedGoods({id:event.currentTarget.dataset.id}).then((result) => {
            wx.showToast({
              title: "订单完成",
              icon: "none",
              mask: false,
              duration: 3000,
              success: () => {
                setTimeout(() => {
                  that.init();
                }, 3000)
              }
            })
          }).catch(err=>{
            wx.showToast({
              title: err.message,
              icon: "none",
              mask: false,
              duration: 3000,
              success: () => {
                setTimeout(() => {
                  that.init();
                }, 3000)
              }
            })
          })
        }
      }
    })
  },

  // 查看订单
  onCheck(event) {
    wx.navigateTo({
      url: `../orderDetails/orderDetails?id=${event.currentTarget.dataset.id}`,
    });
  },

  // 确认收货

  // 查看订单

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})